package com.im.utils;

import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 雪花id生成器
 */
@Component
public class SnowflakeIdGenerator {
    private final long workerId;
    private final long datacenterId;
    private final long sequenceBits = 12L;
    private final long workerIdBits = 5L;
    private final long datacenterIdBits = 5L;
    private final long maxWorkerId = ~(-1L << workerIdBits);
    private final long maxDatacenterId = ~(-1L << datacenterIdBits);
    private final long sequenceMask = ~(-1L << sequenceBits);
    private final long twepoch = 1609459200000L; // 2021-01-01 00:00:00
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator() {
        this.workerId = getWorkerId();
        this.datacenterId = getDatacenterId();
    }

    private long getWorkerId() {
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            return (long) (ip.hashCode() & maxWorkerId);
        } catch (UnknownHostException e) {
            return (long) (Math.random() * maxWorkerId);
        }
    }

    private long getDatacenterId() {
        return (long) (Math.random() * maxDatacenterId);
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨，拒绝生成 ID");
        }
        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                while ((timestamp = System.currentTimeMillis()) <= lastTimestamp) {
                }
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        return ((timestamp - twepoch) << (workerIdBits + datacenterIdBits + sequenceBits))
                | (datacenterId << (workerIdBits + sequenceBits))
                | (workerId << sequenceBits)
                | sequence;
    }
}
